package crm8000.Controllers

import crm8000.services.InitInvertoryService
import crm8000.services.PermissionService
import crm8000.services.UserService
import crm8000.services.WarehouseService
import grails.converters.JSON

class InitInvertoryController {
	static allowedMethods =[warehouseList: 'POST', initInfoList: 'POST',
		goodsCategoryList: 'POST', goodsList: 'POST', commitInitInvertoryGoods: 'POST',
		finish: 'POST', cancel: 'POST']

	PermissionService permissionService

	UserService userService
	
	WarehouseService warehouseService
	
	InitInvertoryService initInvertoryService

	def index() {
		if (!permissionService.hasPermission("2000")) {
			redirect controller: "home"
		}

		[loginUserName: userService.loginUserName]
	}
	
	def warehouseList() {
		def data = warehouseService.warehouseList()
		
		render(contentType: "application/json") { array {
			for (w in data) {
				warehouse id: w.id, code: w.code, name: w.name, inited: w.inited
			}
		}}
	}
	
	def initInfoList() {
		def data = initInvertoryService.initInfoList(params.warehouseId)
		
		render(contentType: "application/json") { array {
			for (item in data) {
				initInfo goodsCode: item.goods.code, goodsName: item.goods.name,
					goodsSpec: item.goods.spec, goodsCount: item.balanceCount,
					goodsUnit: item.goods.unit.name, goodsMoney: item.balanceMoney,
					goodsPrice: item.balancePrice, initDate: item.dateCreated.format("yyyy-MM-dd")
			}
		}}
	}
	
	def goodsCategoryList() {
		def data = initInvertoryService.goodsCategoryList()
		
		render(contentType: "application/json") { array {
			for (item in data) {
				category id: item.id, name: item.name
			}
		}}
	}
	
	def goodsList() {
		def data = initInvertoryService.goodsList(params.categoryId, params.warehouseId)
		
		render(contentType: "application/json") { array {
			for (item in data) {
				goods id: item.id, goodsCode: item.code, goodsName: item.name, goodsSpec: item.spec,
					unitName: item.unit, goodsCount: item.count, goodsPrice: item.price,
					goodsMoney: item.money
			}
		}}
	}
	
	def commitInitInvertoryGoods() {
		def result = initInvertoryService.commitInitInvertoryGoods(params)
		
		render result as JSON
	}
	
	def finish() {
		def result = initInvertoryService.finish(params.warehouseId)
		
		render result as JSON
	}
	
	def cancel() {
		def result = initInvertoryService.cancel(params.warehouseId)
		
		render result as JSON
	}
}
